package com.baiytfp.hf.HFDataExchange.common.utils;

import com.baiytfp.hf.baiytfp.framework.util.PropertiesUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class WebRandomCodeUtils {
	
	public static void productCodeImg(HttpServletRequest request, HttpServletResponse response) throws Exception { 
        response.setHeader("Pragma", "No-cache"); 
        response.setHeader("Cache-Control", "no-cache"); 
        response.setDateHeader("Expires", 0); 
        response.setContentType("image/jpeg"); 
           
        //生成随机字串 
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4); 
       
        //存入会话session 
        HttpSession session = request.getSession(true); 
        //删除以前的
        session.removeAttribute(CommonUtils.RANDOM_CODE_KEY);
        session.setAttribute(CommonUtils.RANDOM_CODE_KEY, verifyCode.toLowerCase()); 
        //生成图片 
        int w = 100, h = 30; 
        VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode); 
   
    } 
	
	
	public static boolean checkCode(String code,HttpServletRequest request) {
		if(isClose() == true)
			return true;

		HttpSession session = request.getSession(true);

		if( !CommonUtils.isEmpty(code) && code.equalsIgnoreCase((String)session.getAttribute(CommonUtils.RANDOM_CODE_KEY))) {
			return true;
		}else {
			return false;
		}
	}

	public static boolean isClose() {
		String is_close = PropertiesUtil.getString("close_verification_code", "false");
		if(is_close.equals("true"))
			return true;
		else if(is_close.equals("false"))
			return false;

		return false;
	}

//	public static boolean
}
